package com.fira.api.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.util.crypt.WxMaCryptUtils;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fira.api.domain.dto.LoginDTO;
import com.fira.api.domain.vo.LoginUserInfoVo;
import com.fira.api.service.IUserService;
import com.fira.common.core.domain.AjaxResult;
import com.fira.system.domain.dto.SysUserMenuDTO;
import com.fira.system.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Deng
 */
@Controller
@RequestMapping(value = "api/weixin")
public class WeiXinController extends ApiController {


    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IUserService userService;

    @Autowired
    private ISysMenuService sysMenuService;

    /**
     * 获取令牌登录
     *
     * @param code
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public AjaxResult wxLogin(String code) {
        try {
            WxMaJscode2SessionResult sessionResult = wxMaService.jsCode2SessionInfo(code);
            String token = IdUtil.fastSimpleUUID();
            LoginDTO loginDTO = new LoginDTO();
            loginDTO.setToken(token);
            loginDTO.setOpenId(sessionResult.getOpenid());
            loginDTO.setSessionKey(sessionResult.getSessionKey());
            loginDTO.setUnionId(sessionResult.getUnionid());
            stringRedisTemplate.opsForValue().set(token, JSONObject.toJSONString(loginDTO));
            return AjaxResult.success(null,token);
        }catch (Exception ex){
            ex.printStackTrace();
            return AjaxResult.error("获取令牌失败！");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getPhone", method = RequestMethod.POST)
    public AjaxResult decryptPhone(HttpServletRequest request, String encryptedData, String ivStr) {
        LoginDTO loginDTO = getLogin(request);
        if (loginDTO == null){
            return AjaxResult.error("获取用户信息失败");
        }
        String decryptStr = WxMaCryptUtils.decryptAnotherWay(loginDTO.getSessionKey(), encryptedData, ivStr);
        JSONObject jsonResult = JSON.parseObject(decryptStr);
        String phone = jsonResult.getString("purePhoneNumber");
        //后续登录逻辑
        AjaxResult result = userService.findUserByPhone(phone, loginDTO);
        if (!result.isSuccess()){
            return result;
        }
        return AjaxResult.success("获取信息成功",initUserInfo(loginDTO));
    }

    private LoginUserInfoVo initUserInfo(LoginDTO loginDTO){
        //获取老师用户菜单
        SysUserMenuDTO sysUserMenuDTO=new SysUserMenuDTO();
        sysUserMenuDTO.setTenantId(loginDTO.getCurrentTenantId());
        sysUserMenuDTO.setUserId(loginDTO.getTeacherId());

        LoginUserInfoVo loginUserInfoVo=new LoginUserInfoVo();
        loginUserInfoVo.setUserName(loginDTO.getTeacherName());
        loginUserInfoVo.setAuths(sysMenuService.selectAppletUserMenu(sysUserMenuDTO));
        stringRedisTemplate.opsForValue().set(loginDTO.getToken(), JSONObject.toJSONString(loginDTO));

        return loginUserInfoVo;
    }




}
